package com.linkage.seapeak.activity.chat;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.adapter.ChatAdapter;
import com.linkage.jz.bankruptcy.bean.Msg;
import com.linkage.jz.bankruptcy.net.BaseSubscriber;
import com.linkage.jz.bankruptcy.net.Network;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.Utils;
import com.linkage.seapeak.activity.message.MultiMessageHistoryActivity;
import com.linkage.seapeak.activity.message.MultiSendActivity;
import com.linkage.seapeak.base.BaseWhiteActivity;
import com.linkage.seapeak.pojo.CrediterUser;
import com.linkage.seapeak.pojo.MessageItem;
import com.linkage.seapeak.utils.ToastUtil;
import com.seapeak.recyclebundle.AYSwipeRecyclerView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * 留言详情展示
 */
public class ChatDetailActivity extends BaseWhiteActivity implements AYSwipeRecyclerView.OnRefreshLoadListener {

    String targetId;
    String targetName;
    String projectId = "";
    String sendUserId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

    private AYSwipeRecyclerView messageList;

    private EditText etContent;
    private TextView btSend;

    private ChatAdapter adapter;
    private List<MessageItem> mDatas;
    private List<MessageItem> adapterData;


    int pageNo = 1;
    int pageSize = 50;

    public static void start(Context context, String targetId, String targetName, String projectId) {
        Intent intent = new Intent(context, ChatDetailActivity.class);
        intent.putExtra("targetId", targetId);
        intent.putExtra("targetName", targetName);
        intent.putExtra("projectId", projectId);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        targetId = getIntent().getStringExtra("targetId");
        targetName = getIntent().getStringExtra("targetName");
        projectId = getIntent().getStringExtra("projectId");

        setContentView(R.layout.activity_chat_detail, "给" + targetName + "留言");
        initView();
        getHistory(true);
    }

    private void initView() {
        mDatas = new ArrayList<>();
        adapterData = new ArrayList<>();
        messageList = (AYSwipeRecyclerView) findViewById(R.id.message_list);
        etContent = (EditText) findViewById(R.id.et_content);
        btSend = (TextView) findViewById(R.id.bt_send);
        adapter = new ChatAdapter(ChatDetailActivity.this, adapterData);
        messageList.setAdapter(adapter);
        messageList.setMode(AYSwipeRecyclerView.SwipeType.ONLY_START);
        messageList.setOnRefreshLoadLister(this);
        messageList.setShowBottomOffset(5000);
        btSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendGroupMsg();
            }
        });
    }

    /**
     * 获取历史消息
     * @param isFirst
     */
    private void getHistory(final boolean isFirst) {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }

        Network.getAPIService()
                .getChatList(getUserToken(), targetId, sendUserId, pageNo, pageSize)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onError(null);
                            return;
                        } else {
                            JsonObject data = json.getAsJsonObject("data");
                            JsonArray array = data.getAsJsonArray("list");
                            List<MessageItem> temp = new ArrayList<>();
                            for (int i = 0;i < array.size();i++) {
                                MessageItem item = new Gson().fromJson(array.get(i), MessageItem.class);
                                String time = Utils.timeStamp2Date(((long) item.getOpAt()) * 1000L, "yyyy-MM-dd HH:mm:ss");
                                item.setSendTime(time);
                                temp.add(item);
                            }

                            if (isFirst) {
                                messageList.setOnRefreshLoadLister(null);
                                mDatas.clear();
                            }
                            mDatas.addAll(temp);
                            int count = data.get("totalCount").getAsInt();
                            adapterData.clear();
                            adapterData.addAll(mDatas);
                            Collections.reverse(adapterData);
                            messageList.onFinishRequest(false, true);
                            if (mDatas.size() == count)
                                messageList.setMode(AYSwipeRecyclerView.SwipeType.ONLY_END);
                            pageNo++;

                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    if (isFirst) {
                                        messageList.getRecyclerView().scrollToPosition(mDatas.size() - 1);
                                        messageList.setOnRefreshLoadLister(ChatDetailActivity.this);
                                    } else
                                        messageList.getRecyclerView().scrollBy(0, -100);
                                }
                            }, 100);
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }
                });
    }

    /**
     * 发送消息
     */
    public void sendGroupMsg() {
        if (BankruptcyApp.tokeninfo == null || BankruptcyApp.tokeninfo.getToken() == null) {
            getToken(null);
            return;
        }

        String contentStr = etContent.getText().toString();
        if (TextUtils.isEmpty(contentStr)) {
            showToast("内容不可以为空");
            return;
        }

        Network.getAPIService()
                .sendLeavingMsg(getUserToken(), projectId, contentStr, targetId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<JsonObject>() {
                    @Override
                    public void onNext(JsonObject json) {
                        int code = json.get("code").getAsInt();
                        if (code != 0) {
                            super.onError(null);
                            return;
                        } else {
                            etContent.setText("");
                            loadNext();
                        }
                    }

                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        showToast("发送失败");
                    }
                });
    }

    @Override
    public void loadFirst() {
        getHistory(false);
    }

    @Override
    public void loadNext() {
        pageNo = 1;
        getHistory(true);
    }
}
